package com.goroom.v4;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 为了弥补v1的缺陷，新建一个静态的map,对于每一个线程，该map都保存一份线程和数据的对应关系
 * 这样再获取的时候，根据线程去获取属于它自己的数据
 * 该例子实现了
 */
public class ThreadLocalV2 {

    private static Map<Thread,Integer> map = new HashMap<Thread, Integer>();

    public static void main(String[] args) {
        for(int i = 0; i < 2; i ++){
            new Thread(){
                @Override
                public void run() {
                    int number = (int)( Math.random() * 10);
                    System.out.println("[" + Thread.currentThread().getName() +"] " +
                            Thread.currentThread().getId() + " generate number: " + number);
                    map.put(Thread.currentThread(), Integer.valueOf(number));
                    new A().get();
                    new B().get();
                }
            }.start();
        }
    }

    static class A{
        public void get(){
            int num = map.get(Thread.currentThread());
            System.out.println("class A " + Thread.currentThread().getName() + ": ==>> " + num );
        }
    }

    static class B{
        public void get(){
            int num = map.get(Thread.currentThread());
            System.out.println("class B " + Thread.currentThread().getName() + " ==>> " + num );
        }
    }
}
